import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';
import store from '../store';

const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject);
  return originalPush.call(this, location).catch(err => err);
};

Vue.use(VueRouter);

const router = new VueRouter({
  routes,
  mode: 'hash',
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { x: 0, y: 0 };
    }
  },
});

// 导航守卫
// 使用 router.beforeEach 注册一个全局前置守卫，判断用户是否登录
router.beforeEach((to, from, next) => {
  if (to.fullPath === '/') {
    next({ path: '/login', query: { redirect: to.fullPath } });
    return;
  }

  if (to.path === '/login') {
    next();
    return;
  }

  // 判断该路由是否需要登录权限
  if (to.matched.some(d => d.meta.isAuth)) {
    if (store.getters['user/user'].token) {  // 通过vuex state获取当前的token是否存在
      // if (store.state.auth.permissions.length === 0) {
      //   const roles = store.state.auth.currentUser.roles;
      //   if (roles && roles.length > 0) {
      //     store.dispatch('auth/getPermissions', { roleIds: roles.map(d => d._id) });
      //   }
      // }
      next();
    } else {
      // 将跳转的路由path作为参数，登录成功后跳转到该路由
      next({ path: '/login', query: { redirect: to.fullPath } });
    }
  } else {
    next();
  }
});

router.beforeResolve(async (routeTo, routeFrom, next) => {
  try {
    for (const route of routeTo.matched) {
      await new Promise((resolve, reject) => {
        if (route.meta && route.meta.beforeResolve) {
          route.meta.beforeResolve(routeTo, routeFrom, (...args) => {
            if (args.length) {
              next(...args);
              reject(new Error('Redirected'));
            } else {
              resolve();
            }
          });
        } else {
          resolve();
        }
      });
    }
  } catch (e) {
    return;
  }

  next();
});

export default router;
